using System;
using System.Collections.Generic;
using CustomORM.Examples.Entities;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Linq;
using NHibernate.Transform;

namespace CustomORM.Examples.CustomORM.vs.NH
{
    public class NhCustomerRepository
    {
        protected ISessionFactory SessionFactory { get; set; }

        public NhCustomerRepository(ISessionFactory sessionFactory)
        {
            SessionFactory = sessionFactory;
            _currentSession = SessionFactory.OpenSession();
        }

        private ISession _currentSession;
        public ISession CurrentSession
        {
            get
            {
                // generally this is bad code, but for now
                if (_currentSession != null && !_currentSession.IsOpen)
                {
                    // if we are not connected, let's open new session...
                    _currentSession = SessionFactory.OpenSession();
                }
                return _currentSession;
            }
        }

        public IList<NhCustomer> FetchAllCustomers()
        {
            var criteria = CurrentSession.CreateCriteria<NhCustomer>()
                .SetResultTransformer(Transformers.DistinctRootEntity);
            var customers = criteria.List<NhCustomer>();

            return customers;
        }

        public NhCustomer Save(NhCustomer customer)
        {
            var beginTransaction = CurrentSession.BeginTransaction();

            var savedCustomerId = CurrentSession.Save(customer);

            beginTransaction.Commit();

            // not returning complete customer at the moment
            return new NhCustomer() {CustomerID = savedCustomerId.ToString()};
        }

        public NhCustomer FetchCustomerByID_Parameter(string customerId)
        {
            var customer = CurrentSession.CreateCriteria<NhCustomer>()
                .Add(Restrictions.Eq("CustomerID",customerId))
                .UniqueResult<NhCustomer>();

            return customer;
        }

        public void Delete(NhCustomer customer)
        {
            var beginTransaction = CurrentSession.BeginTransaction();

            CurrentSession.Delete(customer);

            beginTransaction.Commit();
        }
    }
}